﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CollegeShop.Biz;
using CollegeShop.Infrastructure.Entities.Enum;
using System.Web.Security;
using CollegeShop.WebProcessor;
using CollegeShop.Infrastructure.Entities.Entity;

namespace CollegeShop.Web.Controllers
{
    [ErrorHandle]
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult SignIn()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SignIn(string username, string password, string remberme)
        {
            if (String.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                ViewBag.Error = "输入有误，请重新输入";
                return View();
            }
            var user = new User().Find(username);
            if (user == null)
            {
                ViewBag.Error = "该用户不存在，请确认用户名";
                return View();
            }
            if (user.Password != CollegeShop.Tool.Framework.AesAlgorithm.Encrypt(password))
            {
                ViewBag.Error = "用户名或密码错误，请重新输入";
                return View();
            }
            System.Web.Security.FormsAuthentication.SetAuthCookie(username, remberme == "true");
            string returnUrl = Request.Form["ReturnUrl"];
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return Redirect("/");
        }
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Register(string username, string password, string nickname)
        {
            string message = UserBiz.Register(username, password, nickname);
            if (!String.IsNullOrEmpty(message))
            {
                ViewBag.Error = message;
                return View();
            }
            FormsAuthentication.SetAuthCookie(username, false);
            return Redirect("/");
        }
        //执行本机登陆
        public int LocalLogin(string code)
        {
            return UserBiz.LocalLogin(code, ClientType.Browser);
        }
        public ActionResult SignOut(string returnurl)
        {
            System.Web.Security.FormsAuthentication.SignOut();
            if (!String.IsNullOrEmpty(returnurl))
            {
                return Redirect(returnurl);
            }
            return Redirect("/");
        }
        /// <summary>
        /// 如果验证用户名为不存在返回 true
        ///              否则返回 false
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool usernameonly(string userName)
        {
            var exists = UserBiz.UserNotExists(userName);
            return exists;
        }
    }
}
